<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :title="title"
    :visible="visible"
    :width="1200"
    cancelText="关闭"
    switchFullscreen
    @cancel="handleCancel"
    @ok="handleOk">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="!disableSubmit" :loading='confirmLoading' type="primary" @click="handleOk">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :lg="12" :md="12" :sm="24" :xl="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="活动标题">
              <a-input v-decorator="['actName',  validatorRules.actName]" :disabled="disableSubmit" placeholder="请输入活动标题"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="活动内容">
              <a-textarea v-decorator="['actContent',validatorRules.actContent]" :disabled="disableSubmit" placeholder="请输入活动内容"/>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="24" :xl="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="活动时间">
              <a-range-picker v-decorator="['actStart', validatorRules.actStart]" :format="'YYYY-MM-DD'"
                              :disabled="disableSubmit" :placeholder="['开始时间','结束时间']"
                              :valueFormat="'YYYY-MM-DD'"
                              @change="dateRangeChange" style="width: 100%"></a-range-picker>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="执行要求">
              <a-textarea v-decorator="['actExecNeeds', validatorRules.actExecNeeds]" :disabled="disableSubmit" placeholder="请输入执行要求"/>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="24" :xl="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="活动范围">
              <cn-dict-select-tag v-decorator="['haveScope',validatorRules.haveScope]" :disabled="disableSubmit"
                                  :options="{value:'dictDataCode',label:'dictDataDesc'}" :triggerChange="true"
                                  dictCode="ishave"
                                  placeholder="门店清单" @change="changeTerm"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <!-- 活动明细 -->
    <a-tabs v-if="showterm" v-model="activeKey">
      <!--      <a-tabs v-model="tabs.activeKey">-->
      <a-tab-pane key="terminal" forceRender tab="门店范围">
        <row-edit-table
          ref="customerNTable"
          rowKey="terminalCode"
          :chooseUrl="url.terminal"
          :addButton="!disableSubmit"
          :disableDelete="disableSubmit"
          mode="checkBox"
          :data.sync="terminalList"
          :columns="terminalColumns"
          :tableHeight="200"
          :chooseColumns="terminalColumnsChoose"
          :conditions="[{ label: '门店编号', field: 'terminalCode' },
          { label: '门店名称', field: 'terminalName' }, { label: '省', field: 'province' },
          { label: '市', field: 'city' }, { label: '区', field: 'area' }]"
        ></row-edit-table>
      </a-tab-pane>
      <a-tab-pane key="cust" forceRender tab="经销商范围">
        <row-edit-table
          ref="customerNTable"
          rowKey="custCode"
          :chooseUrl="url.cust"
          :addButton="!disableSubmit"
          :disableDelete="disableSubmit"
          mode="checkBox"
          :data.sync="custList"
          :columns="custColumns"
          :tableHeight="200"
          :chooseColumns="custColumnsChoose"
          :conditions="[{ label: '经销商编号', field: 'custCode' }, { label: '经销商名称', field: 'custName' }]"
        ></row-edit-table>
      </a-tab-pane>

      <a-tab-pane key="org" forceRender tab="组织范围">
        <row-edit-table
          ref="customerNTable"
          rowKey="orgCode"
          :chooseUrl="url.orgurl"
          :addButton="!disableSubmit"
          :disableDelete="disableSubmit"
          mode="checkBox"
          :data.sync="orgList"
          :columns="orgColumns"
          :tableHeight="200"
          :chooseColumns="orgColumnsChoose"
          :conditions="[{ label: '组织编号', field: 'orgCode' }, { label: '组织名称', field: 'orgName' }]"
        ></row-edit-table>
        <!--        <tpm-act-special-detail-list  :tempUuid="this.tempUuid" @ok='dataList'></tpm-act-special-detail-list>-->
      </a-tab-pane>

    </a-tabs>
  </j-modal>

</template>
<script>
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import { httpAction, postAction } from '@/api/manage'
import pick from 'lodash.pick'
import TpmActSpecialDetailList from '@views/tpm/act/TpmActSpecialDetailList'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
import { PageListMixin } from '@/mixins/PageListMixin'
import JImageUpload from '@/components/cn-form/JImageUpload'
import RowEditTable from '@/components/cn-components/RowEditTable'

export default {
  name: 'TpmActSpecialModal',
  components: {
    JImageUpload,
    RowEditTable,
    JTreeSelect,
    TpmActSpecialDetailList,
    JMultiSelectTag
  },
  mixins: [PageListMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      tempUuid: '',
      custList: [],
      terminalList: [],
      orgList: [],
      execDetailVo: [], //门店清单
      showterm: false,
      showorg: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      activeKey: 'terminal',
      orgColumns: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode',
          width: 100
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      custColumnsChoose: [
        {
          title: '经销商编号',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        }
      ],
      custColumns: [
        {
          title: '经销商编号',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      terminalColumns: [
        {
          title: '门店编号',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '省',
          align: 'center',
          dataIndex: 'province'
        },
        {
          title: '市',
          align: 'center',
          dataIndex: 'city'
        },
        {
          title: '区',
          align: 'center',
          dataIndex: 'area'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      orgColumnsChoose: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode'

        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'

        }
      ],
      terminalColumnsChoose: [
        {
          title: '门店编号',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '省',
          align: 'center',
          dataIndex: 'province'
        },
        {
          title: '市',
          align: 'center',
          dataIndex: 'city'
        },
        {
          title: '区',
          align: 'center',
          dataIndex: 'area'
        },
      ],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        actName: { rules: [{ required: true, message: '请输入活动名称!' }] },
        actContent: { rules: [{ required: true, message: '请输入活动内容!' }] },
        actCollections: { rules: [{ required: true, message: '' }] },
        haveScope: { rules: [{ required: true, message: '请选择是否有门店清单!' }] },
        actExecNeeds: { rules: [{ required: true, message: '请输入执行要求!' }] },
        actStart: { rules: [{ required: true, message: '请选择活动时间!' }] },
        actFileUrl: { rules: [{ required: true, message: '请上传示例文件!' }] },
      },
      url: {
        terminal: window._CONFIG['domianURL'] + '/cnTerminalController/custFindTerminalList',
        cust: window._CONFIG['domianURL'] + '/customerController/getPageList',
        orgurl: window._CONFIG['domianURL'] + '/cnOrgController/findTreeList',
        add: window._CONFIG['domianSfaURL'] + '/act/tpmActSpecial/saveOrUpdate',
        edit: window._CONFIG['domianSfaURL'] + '/act/tpmActSpecial/saveOrUpdate',
      },
    }
  },
  created() {
  },
  methods: {
    dataList(e) {
      this.dataSource = e
      console.log(this.dataSource)
    },
    add() {
      this.edit({})
    },
    edit(record) {
      if (record.tempUuid == undefined || record.tempUuid == '') {
        if (record.id != undefined && record.id != null) {
          this.tempUuid = record.id
        } else {
          this.tempUuid = this.generateUUID(false)
        }
      } else {
        this.tempUuid = record.tempUuid
      }
      this.form.resetFields()
      this.model = Object.assign({}, record)
      if (this.model.haveScope != undefined && this.model.haveScope == 1) {
        this.showterm = true
        this.showorg = false
      } else {
        this.showterm = false
        this.showorg = true
      }
      if (this.model.actStart != undefined) {
        let arr = []
        arr.push(this.model.actStart)
        arr.push(this.model.actEnd)
        this.model.actStart = arr
      }
      if (record.id) {
        let execDetailVo = record.execDetailVo||[]
        execDetailVo.forEach(item =>{
          if(item.dataType === 1){
            item.orgName = item.name
            item.orgCode = item.code
            this.orgList = execDetailVo
          }
          if(item.dataType === 2){
            item.terminalCode = item.name
            item.terminalName = item.code
            item.province=item.provinceOrgName, //省
            item.city=item.cityOrgName,  //市
            item.area=item.dqOrgName,   //区
            this.terminalList = execDetailVo
          }
          if(item.dataType === 3){
            item.custCode = item.name
            item.custName = item.code
            this.custList = execDetailVo
          }
        })
        console.log(execDetailVo)
        // this.orgList = execDetailVo.map(item => item.dataType == 1)
        // this.terminalList = execDetailVo.map(item => item.dataType == 2)
        // this.custList = execDetailVo.map(item => item.dataType == 3)
        if(this.orgList.length){
          this.activeKey = 'org'
        } else if(this.custList.length){
          this.activeKey = 'cust'
        }else {
          this.activeKey = 'terminal'
        }
      }
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'actOrgs', 'tempUuid', 'actCode', 'actName', 'actStart', 'actEnd', 'actContent', 'actExecNeeds', 'actCollections', 'haveScope', 'actFileUrl'))
        //时间格式化
      })

    },
    close() {
      this.$emit('close')
      this.custList = []
      this.terminalList = []
      this.orgList = []
      this.activeKey = 'terminal'
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          httpurl += this.url.add
          method = 'post'
          let dataSource = this.dataSource.map(type => Object.assign({
            terminalCode: type.terminalCode,
            terminalName: type.terminalName,
            provinceOrgName: type.province, //省
            cityOrgName: type.city,  //市
            dqOrgName: type.area   //区
          }))
          let list = [...this.terminalList.map(item => Object.assign({
            terminalCode: item.terminalCode,
            terminalName: item.terminalName,
            provinceOrgName: item.province, //省
            cityOrgName: item.city,  //市
            dqOrgName: item.area,  //区
            dataType: 2
          })), ...this.orgList.map(item => Object.assign({
            orgName: item.orgName,
            orgCode: item.orgCode,
            dataType: 1
          })), ...this.custList.map(item => Object.assign({
            custCode: item.custCode,
            custName: item.custName,
            dataType: 3
          }))]
          // console.log(list)
          let formData = Object.assign(this.model, values)
          if (this.activeKey == 'terminal') {
            formData.execDetailVo = this.terminalList.map(item => Object.assign({
              code: item.terminalCode,
              name: item.terminalName,
              provinceOrgName: item.province, //省
              cityOrgName: item.city,  //市
              dqOrgName: item.area,  //区
              dataType: 2
            }))
            console.log(this.terminalList)
          }
          if (this.activeKey == 'org') {
            console.log(this.orgList)
            debugger
            formData.execDetailVo = this.orgList.map(item => Object.assign({
              name: item.orgName,
              code: item.orgCode,
              dataType: 1
            }))
          }
          if (this.activeKey == 'cust') {
            formData.execDetailVo = this.custList.map(item => Object.assign({
              code: item.custCode,
              name: item.custName,
              dataType: 3
            }))
          }
          formData.tempUuid = this.tempUuid
          formData.actEnd = formData.actStart[1]
          formData.actStart = formData.actStart[0]
          that.confirmLoading = true
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.close()
      this.showterm = false
    },
    changeTerm(val) {
      if (val != undefined) {
        if (val === '' || val === '0') {
          this.showterm = false
          this.showorg = true
        } else {
          this.showterm = true
          this.showorg = false
        }
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>